// pages/engage/engage.js
const app = getApp();
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabKey: 0,
    city: ['广东省', '中山市'],
    firstJobs: new Array(0),
    secondJobs: new Array(0),
    thirdJobs: new Array(0),
    fourthJobs: new Array(0),
    topNum: 0,
    myOpacity: 0,
    rocketPosition: '15%',
    swiperHeight: 0,
    slidingBlockProgress: 0
  },
  // -----methods   start--------//
  bindRegionChange(e) {
    // console.log(e);
    this.setData({
      city: e.detail.value
    })
    // 做一下缓存
    wx.setStorageSync("city", JSON.stringify(this.data.city));
    console.log(e.detail.value);
    this.refresh();
  },
  scrolltoupper(e) {
    let that = this;
    if (e.detail.scrollTop >= 200) {
      that.setData({
        myOpacity: 100,
        rocketPosition: '15%'
      });
    } else {
      that.setData({
        myOpacity: 0,
      });
    }
    // if (e.detail.scrollTop == 0) {
    //   that.setData({
    //     rocketPosition: '15%'
    //   });
    // }


    // console.log(e.detail.scrollTop);

  },
  toTheTop() {
    console.log("返回顶部");
    this.setData({
      topNum: 0, //返回顶部
      rocketPosition: '68%' //火箭上移
    });
  },
  navToDetail(e) {
    console.log(e.currentTarget.dataset);
    let i = e.currentTarget.dataset.i;
    let tmpData = e.currentTarget.dataset.origin;
    let conveyData;
    if (tmpData == 'firstJobs') {
      conveyData = this.data.firstJobs[i];
    } else if (tmpData == 'secondJobs') {
      conveyData = this.data.secondJobs[i];
    } else if (tmpData == 'thirdJobs') {
      conveyData = this.data.thirdJobs[i];
    } else if (tmpData == 'fourthJobs') {
      conveyData = this.data.fourthJobs[i];
    }
    // console.log(tmpData);
    // console.log(conveyData);
    app.navTmpInfo = conveyData;
    wx.navigateTo({
      url: '/pages/job_detail/job_detail'
    })
  },
  navToSearch() {
    console.log("搜索");
    wx.navigateTo({
      url: '/pages/searchJob/searchJob',
    })
  },
  handleChange(e) {
    this.setData({
      tabKey: e.detail.key
    });
    // console.log('tabKey:' + e.detail.key);
  },
  handleSwiperItemChange(e) {
    this.setData({
      tabKey: e.detail.current
    });
    // console.log('tabKey:' + e.detail.current);
  },
  watch: {
    tabKey: function (newValue, oldValue) {
      // console.log(typeof newValue);
      var that = this;
      // console.log("tabKey新值：" + newValue);
      let length;
      switch (newValue) {
        case 0: {
          length = that.data.firstJobs.length;
          // console.log(that.data.firstJobs);
          break;
        }
        case 1: {
          length = that.data.secondJobs.length;
          // console.log(that.data.secondJobs);
          break;
        }
        case 2: {
          length = that.data.thirdJobs.length;
          // console.log(that.data.thirdJobs);
          break;
        }
        case 3: {
          length = that.data.fourthJobs.length;
          // console.log(that.data.fourthJobs);
          break;
        }
      }
      // console.log(whichList);
      var query = wx.createSelectorQuery();
      query.select('.itemStyle').boundingClientRect();
      query.exec(function (res2) {
        // console.log(res2[0]);
        if (res2[0]) {
          that.setData({
            swiperHeight: length * (res2[0].height + 40) + 'px'
          })
        }
        // console.log(that.data.swiperHeight);
      })
    },

    firstJobs: function (newValue, oldValue) {
      // console.log(this.data.firstJobs);
      //处理第一次加载无法刷新高度的问题
      this.setData({
        tabKey: 0
      })
    },
    secondJobs: function (newValue, oldValue) {
      let a = this.data.secondJobs; //访问一下
    },
    thirdJobs: function (newValue, oldValue) {
      let a = this.data.thirdJobs; //访问一下
    },
    fourthJobs: function (newValue, oldValue) {
      let a = this.data.fourthJobs; //访问一下
    }
  },

  //刷新数据
  refresh() {
    //先做一遍清空
    this.setData({
      firstJobs: new Array(0),
      secondJobs: new Array(0),
      thirdJobs: new Array(0),
      fourthJobs: new Array(0),
    })
    let that = this;
    wx.showLoading({
      title: '加载中',
    });
    let aQuery = wx.createSelectorQuery();
    aQuery.select('.scrollView').boundingClientRect();
    // console.log(aQuery);

    wx.cloud.callFunction({
      name: 'getAllRecord',
      data: {
        collectionName: 'job'
      },
      success: res => {
        // console.log(res.result.all);
        // console.log("共" + res.result.all.length + "条记录");
        let MatchCity = []
        for (let i = 0; i < res.result.all.length; i++) {
          if (res.result.all[i].city == that.data.city[1]) {
            MatchCity.push(res.result.all[i])
          }
        }
        // console.log(MatchCity);
        for (let i = 0; i < MatchCity.length; i++) {
          switch (MatchCity[i].type) {
            case '数字建设': {
              let tmp = that.data.firstJobs;
              tmp.push(MatchCity[i]);
              that.setData({
                firstJobs: tmp
              })
              break;
            }
            case '农业技术': {
              let tmp = that.data.secondJobs;
              tmp.push(MatchCity[i]);
              that.setData({
                secondJobs: tmp
              })

              break;
            }
            case '农业工程技术': {
              let tmp = that.data.thirdJobs;
              tmp.push(MatchCity[i]);
              that.setData({
                thirdJobs: tmp
              })

              break;
            }
            case '乡村工匠专业': {
              let tmp = that.data.fourthJobs;
              tmp.push(MatchCity[i]);
              that.setData({
                fourthJobs: tmp
              })

              break;
            }
          }
        }
      },
      fail: res => {
        console.log(res);
        console.log("获取数据失败")
      },
      complete: res => {
        wx.hideLoading()
      }
    })
  },




  /**
   * 生命周期函数--监听页面加载
   */

  async onLoad(options) {
    if (wx.getStorageSync("city")) {
      this.setData({
        city: JSON.parse(wx.getStorageSync("city"))
      })
    }



    this.refresh();
    getApp().setWatcher(this.data, this.watch, this); // 设置监听器类似Vue中的watch

  },
  // -----methods   end--------//


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

    //实现推送
    // console.log("onReady");
    // const templateId = 'ZsVNF1tKYrk_isoYXtWlj2UCpAqAdlHYfDMLOTihRhY' //模板ID
    // const openid = getApp().openid // 用户的openid
    // db.collection('subscribeRecord').where({ //查找数据库中模板ID对应未发送的记录
    //   _openid: openid,
    //   status: 0,
    //   templateId: templateId
    // }).limit(1).get({
    //   success: res => {
    //     console.log(res.data[0]);
    //     const id = res.data[0]._id //存储该条数据的id
    //     // 调用云函数发送订阅消息
    //     wx.cloud.callFunction({
    //       name: "subscribe",
    //       data: res.data[0]
    //     }).then(res => {
    //       console.log("推送成功", res);
    //       // 根据id修改该条数据状态，设置为已发送
    //       db.collection('subscribeRecord').where({
    //         _id: id
    //       }).update({
    //         data: {
    //           status: 1
    //         }
    //       })
    //     }).catch(res => {
    //       console.log(res)
    //     })
    //   },
    //   fail: err => {
    //     wx.showToast({
    //       icon: 'none',
    //       title: '查询订阅消息记录失败'
    //     })
    //   }
    // });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // console.log("onshow");
    this.getTabBar().setData({
      curIndex: '1'
    });

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {


  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})